package com.peza.bikelog.web.controllers;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.peza.bikelog.business.service.BikelogService;
import com.peza.bikelog.common.domain.LogEntry;
import com.peza.bikelog.common.json.JsonService;

@Controller
public class RequestController {

	private static Logger logger = Logger.getLogger(RequestController.class); 
	
	@Autowired
	private BikelogService logService;

	@Autowired
	private JsonService jsonService;

	@RequestMapping(value = "/entry/{id}", method = RequestMethod.GET)
	@ResponseBody
	public LogEntry selectOne(@PathVariable Long id) {
		logger.debug("selectOne with parameter [" + id + "]");
		LogEntry entry = logService.getLogEntry(id);
		logger.debug(entry);
		return entry;
	}
	
	@RequestMapping(value = "/entries/{from}/{to}", method = RequestMethod.GET)
	@ResponseBody
	public List<LogEntry> selectRange(@PathVariable Long from, @PathVariable Long to) {
		logger.debug("selectRange with parameters [" + from +" - " + to + "]");
		List<LogEntry> entries = logService.getLogEntryRange(from, to); 
		logger.debug(entries);
		return entries;
	}
	
	@RequestMapping(value = "/entries/all", method = RequestMethod.GET)
	@ResponseBody
	public List<LogEntry> selectAll(@PathVariable Long from, @PathVariable Long to) {
		logger.debug("selectRange with parameters [" + from +" - " + to + "]");
		List<LogEntry> entries = logService.getLogEntryRange(from, to); 
		logger.debug(entries);
		return entries;
	}
	
	@RequestMapping(value = "/entry/update", method = RequestMethod.POST)
	@ResponseBody
	public LogEntry update(@RequestBody LogEntry entry) {
		logger.debug("updating  [" + entry + "]");
		logService.saveLogEntry(entry);
		return entry;
	}
	
	@RequestMapping(value = "/entries/update", method = RequestMethod.POST)
	public void updateAll(@RequestBody LogEntry[] entries) {
		logger.debug("updating  [" + entries + "]");
		for (LogEntry entry : entries){
			logService.saveLogEntry(entry);
		}
	}
	
	@RequestMapping(value = "/entries/update", method = RequestMethod.PUT)
	public void create(@RequestBody LogEntry entry) {
		logger.debug("creating  [" + entry + "]");
		logService.saveLogEntry(entry);
	}
	
	@RequestMapping(value = "/entry/remove", method = RequestMethod.PUT)
	public void remove(@RequestBody LogEntry entry) {
		logger.debug("removing  [" + entry + "]");
		logService.deleteLogEntry(entry.getId());
		
	}




	

}
